<?php

/**
 *   OPENSHOP 商品管理程序
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: goods.php,v 1.0 2009/06/12 07:35:58 modified $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . '/admin/includes/lib_goods.php');

$exc = new exchange($os->table("goods"), $db, 'goods_id', 'goods_name');

/* 是否启用商品预售、承诺发货天数、自动定义热销款 */
$smarty->assign('use_presale', $_CFG['use_presale']);
$smarty->assign('use_promise_delivery', $_CFG['use_promise_delivery']);
$smarty->assign('use_auto_hot', $_CFG['use_auto_hot']);

/*------------------------------------------------------ */
//-- 商品列表，商品回收站
/*------------------------------------------------------ */

$smarty->assign("act",$_REQUEST['act']);

if ($_REQUEST['act'] == 'list' || $_REQUEST['act'] == 'trash')
{
	//检查权限
	admin_priv();

	/* XX天，日均销售量达到YY的商品，自动定义为热销款 */
	if($_CFG['use_auto_hot']) { auto_set_hot(); }

	$cat_id = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
	$code   = empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);

	$handler_list = array();
	$handler_list['virtual_card'][] = array('url'=>'virtual_card.php?act=card', 'title'=>'查看虚拟卡信息', 'img'=>'icon_send_bonus.gif');
	$handler_list['virtual_card'][] = array('url'=>'virtual_card.php?act=replenish', 'title'=>'补货', 'img'=>'icon_add.gif');
	$handler_list['virtual_card'][] = array('url'=>'virtual_card.php?act=batch_card_add', 'title'=>'批量补货', 'img'=>'icon_output.gif');

	if ($_REQUEST['act'] == 'list' && isset($handler_list[$code]))
	{
		$smarty->assign('add_handler',      $handler_list[$code]);
	}

	/* 模板赋值 */
	$goods_ur = array('' => '商品列表', 'virtual_card'=>'虚拟卡列表');
	$ur_here = ($_REQUEST['act'] == 'list') ? $goods_ur[$code] : '商品回收站';
	$smarty->assign('ur_here', $ur_here);

	$action_link = ($_REQUEST['act'] == 'list') ? add_link($code) : array('href' => 'goods.php?act=list', 'text' => '商品列表');
	$smarty->assign('action_link',  $action_link);
	$smarty->assign('code',     	$code);
	$smarty->assign('cat_list',     cat_list(0, $cat_id));
	$smarty->assign('brand_list',   get_brand_list());
	$intro_list = get_intro_list();
	if($_CFG['use_presale']) { $intro_list['is_presale'] = $GLOBALS['_LANG']['is_presale']; }
	$smarty->assign('intro_list',   $intro_list);
	$smarty->assign('list_type',    $_REQUEST['act'] == 'list' ? 'goods' : 'trash');
	$smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);

	$goods_list = goods_list($_REQUEST['act'] == 'list' ? 0 : 1, ($_REQUEST['act'] == 'list') ? (($code == '') ? 1 : 0) : -1);
	//make_json_error($goods_list);
	$smarty->assign('goods_list',   $goods_list['goods']);
	$smarty->assign('filter',       $goods_list['filter']);
	$smarty->assign('record_count', $goods_list['record_count']);
	$smarty->assign('page_count',   $goods_list['page_count']);
	$smarty->assign('full_page',    1);

	/* 排序标记 */
	$sort_flag  = sort_flag($goods_list['filter']);
	$smarty->assign($sort_flag['tag'], $sort_flag['img']);

	/* 显示商品列表页面 */
	assign_query_info();
	$htm_file = ($_REQUEST['act'] == 'list') ?
	'goods_list.tpl' : (($_REQUEST['act'] == 'trash') ? 'goods_trash.tpl' : 'group_list.tpl');
	$smarty->display($htm_file);
}

/*------------------------------------------------------ */
//-- 添加新商品 编辑商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit' || $_REQUEST['act'] == 'copy')
{
	include_once(ROOT_PATH . 'includes/fckeditor/fckeditor.php'); // 包含 html editor 类文件

	$is_add = $_REQUEST['act'] == 'add'; // 添加还是编辑的标识
	$is_copy = $_REQUEST['act'] == 'copy'; //是否复制
	$code = empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
	if ($code == 'virual_card')
	{
		admin_priv('virualcard'); // 检查权限
	}
	else
	{
		$priv_str = $is_add ? 'add_goods' : ($_REQUEST['act'] == 'edit' ? 'edit_goods' : 'add_goods');
		if($_REQUEST['act'] == 'copy'){
			$priv_str = 'copy_goods';
		}
		admin_priv($priv_str);
	}

	/* 如果是安全模式，检查目录是否存在 */
	if (ini_get('safe_mode') == 1 && (!file_exists('../' . IMAGE_DIR . '/'.date('Ym')) || !is_dir('../' . IMAGE_DIR . '/'.date('Ym'))))
	{
		if (@!mkdir('../' . IMAGE_DIR . '/'.date('Ym'), 0777))
		{
			$warning = sprintf('您的服务器运行在安全模式下，而且 %s 目录不存在。您可能需要先行创建该目录才能上传图片。', '../' . IMAGE_DIR . '/'.date('Ym'));
			$smarty->assign('warning', $warning);
		}
	}

	/* 如果目录存在但不可写，提示用户 */
	elseif (file_exists('../' . IMAGE_DIR . '/'.date('Ym')) && file_mode_info('../' . IMAGE_DIR . '/'.date('Ym')) < 2)
	{
		$warning = sprintf('目录 %s 不可写，您需要把该目录设为可写才能上传图片。', '../' . IMAGE_DIR . '/'.date('Ym'));
		$smarty->assign('warning', $warning);
	}

	/* 取得商品信息 */
	if ($is_add)
	{
		/* 默认值 */
		$last_choose = array(0, 0);
		if (!empty($_COOKIE['OSCP']['last_choose']))
		{
			$last_choose = explode('|', $_COOKIE['OSCP']['last_choose']);
		}
		$goods = array(
		'goods_id'      => 0,
		'goods_desc'    => '',
		'cat_id'        => $last_choose[0],
		'brand_id'      => $last_choose[1],
		'is_on_sale'    => '1',
		'is_alone_sale' => '1',
		'other_cat'     => array(), // 扩展分类
		'goods_type'    => 0,       // 商品类型
		'shop_price'    => 0,
		'promote_price' => 0,
		'market_price'  => 0,
		'integral'      => 0,
		'goods_number'  => $_CFG['default_storage'],
		'warn_number'   => 1,
		'promote_start_date' => local_date('Y-m-d'),
		'promote_end_date'   => local_date('Y-m-d', local_strtotime('+1 month')),
		'goods_weight'  => 0,
		'give_integral' => -1,
		'rank_integral' => -1
		);

		if ($code != '')
		{
			$goods['goods_number'] = 0;
		}

		/* 关联商品 */
		$link_goods_list = array();
		$sql = "DELETE FROM " . $os->table('link_goods') .
		" WHERE (goods_id = 0 OR link_goods_id = 0)" .
		" AND admin_id = '$_SESSION[admin_id]'";
		$db->query($sql);

		/* 组合商品 */
		$group_goods_list = array();
		$sql = "DELETE FROM " . $os->table('group_goods') .
		" WHERE parent_id = 0 AND admin_id = '$_SESSION[admin_id]'";
		$db->query($sql);

		/* 关联文章 */
		$goods_article_list = array();
		$sql = "DELETE FROM " . $os->table('goods_article') .
		" WHERE goods_id = 0 AND admin_id = '$_SESSION[admin_id]'";
		$db->query($sql);

		/* 属性 */
		$sql = "DELETE FROM " . $os->table('goods_attr') . " WHERE goods_id = 0";
		$db->query($sql);

		/* 图片列表 */
		$img_list = array();
	}
	else
	{
		/* 商品信息 */
		$sql = "SELECT * FROM " . $os->table('goods') . " WHERE goods_id = '$_REQUEST[goods_id]'";
		$goods = $db->getRow($sql);

		/* 虚拟卡商品复制时, 将其库存置为0*/
		if ($is_copy && $code != '')
		{
			$goods['goods_number'] = 0;
		}

		if (empty($goods) === true)
		{
			/* 默认值 */
			$goods = array(
			'goods_id'      => 0,
			'goods_desc'    => '',
			'cat_id'        => 0,
			'is_on_sale'    => '1',
			'is_alone_sale' => '1',
			'other_cat'     => array(), // 扩展分类
			'goods_type'    => 0,       // 商品类型
			'shop_price'    => 0,
			'promote_price' => 0,
			'market_price'  => 0,
			'integral'      => 0,
			'goods_number'  => 1,
			'warn_number'   => 1,
			'promote_start_date' => local_date('Y-m-d'),
			'promote_end_date'   => local_date('Y-m-d', gmstr2tome('+1 month')),
			'goods_weight'  => 0,
			'give_integral' => -1,
			'rank_integral' => -1
			);
		}

		/* 根据商品重量的单位重新计算 */
		if ($goods['goods_weight'] > 0)
		{
			$goods['goods_weight_by_unit'] = ($goods['goods_weight'] >= 1) ? $goods['goods_weight'] : ($goods['goods_weight'] / 0.001);
		}

		if (!empty($goods['goods_brief']))
		{
			//$goods['goods_brief'] = trim_right($goods['goods_brief']);
			$goods['goods_brief'] = $goods['goods_brief'];
		}
		if (!empty($goods['keywords']))
		{
			//$goods['keywords']    = trim_right($goods['keywords']);
			$goods['keywords']    = $goods['keywords'];
		}

		/* 如果不是促销，处理促销日期 */
		if (isset($goods['is_promote']) && $goods['is_promote'] == '0')
		{
			unset($goods['promote_start_date']);
			unset($goods['promote_end_date']);
		}
		else
		{
			$goods['promote_start_date'] = local_date('Y-m-d', $goods['promote_start_date']);
			$goods['promote_end_date'] = local_date('Y-m-d', $goods['promote_end_date']);
		}

		/* 如果是复制商品，处理 */
		if ($_REQUEST['act'] == 'copy')
		{
			// 商品信息
			$goods['goods_id'] = 0;
			$goods['goods_sn'] = '';
			$goods['goods_name'] = '';
			$goods['goods_img'] = '';
			$goods['goods_thumb'] = '';
			$goods['original_img'] = '';

			// 扩展分类不变

			// 关联商品
			$sql = "DELETE FROM " . $os->table('link_goods') .
			" WHERE (goods_id = 0 OR link_goods_id = 0)" .
			" AND admin_id = '$_SESSION[admin_id]'";
			$db->query($sql);

			$sql = "SELECT '0' AS goods_id, link_goods_id, is_double, '$_SESSION[admin_id]' AS admin_id" .
			" FROM " . $os->table('link_goods') .
			" WHERE goods_id = '$_REQUEST[goods_id]' ";
			$res = $db->query($sql);
			while ($row = $db->fetchRow($res))
			{
				$db->autoExecute($os->table('link_goods'), $row, 'INSERT');
			}

			$sql = "SELECT goods_id, '0' AS link_goods_id, is_double, '$_SESSION[admin_id]' AS admin_id" .
			" FROM " . $os->table('link_goods') .
			" WHERE link_goods_id = '$_REQUEST[goods_id]' ";
			$res = $db->query($sql);
			while ($row = $db->fetchRow($res))
			{
				$db->autoExecute($os->table('link_goods'), $row, 'INSERT');
			}

			// 配件
			$sql = "DELETE FROM " . $os->table('group_goods') .
			" WHERE parent_id = 0 AND admin_id = '$_SESSION[admin_id]'";
			$db->query($sql);

			$sql = "SELECT 0 AS parent_id, goods_id, goods_price, '$_SESSION[admin_id]' AS admin_id " .
			"FROM " . $os->table('group_goods') .
			" WHERE parent_id = '$_REQUEST[goods_id]' ";
			$res = $db->query($sql);
			while ($row = $db->fetchRow($res))
			{
				$db->autoExecute($os->table('group_goods'), $row, 'INSERT');
			}

			// 关联文章
			$sql = "DELETE FROM " . $os->table('goods_article') .
			" WHERE goods_id = 0 AND admin_id = '$_SESSION[admin_id]'";
			$db->query($sql);

			$sql = "SELECT 0 AS goods_id, article_id, '$_SESSION[admin_id]' AS admin_id " .
			"FROM " . $os->table('goods_article') .
			" WHERE goods_id = '$_REQUEST[goods_id]' ";
			$res = $db->query($sql);
			while ($row = $db->fetchRow($res))
			{
				$db->autoExecute($os->table('goods_article'), $row, 'INSERT');
			}

			// 图片不变

			// 商品属性
			$sql = "DELETE FROM " . $os->table('goods_attr') . " WHERE goods_id = 0";
			$db->query($sql);

			$sql = "SELECT 0 AS goods_id, attr_id, attr_value, attr_price " .
			"FROM " . $os->table('goods_attr') .
			" WHERE goods_id = '$_REQUEST[goods_id]' ";
			$res = $db->query($sql);
			while ($row = $db->fetchRow($res))
			{
				$db->autoExecute($os->table('goods_attr'), addslashes_deep($row), 'INSERT');
			}
		}

		// 扩展分类
		$other_cat_list = array();
		$sql = "SELECT cat_id FROM " . $os->table('goods_cat') . " WHERE goods_id = '$_REQUEST[goods_id]'";
		$goods['other_cat'] = $db->getCol($sql);
		foreach ($goods['other_cat'] AS $cat_id)
		{
			$other_cat_list[$cat_id] = cat_list(0, $cat_id);
		}
		$smarty->assign('other_cat_list', $other_cat_list);

		$link_goods_list    = get_linked_goods($goods['goods_id']); // 关联商品
		$group_goods_list   = get_group_goods($goods['goods_id']); // 配件
		$goods_article_list = get_goods_articles($goods['goods_id']);   // 关联文章

		/* 商品图片路径 */
		if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 10) && !empty($goods['original_img']))
		{
			$goods['goods_img'] = get_image_path($_REQUEST['goods_id'], $goods['goods_img']);
			$goods['goods_thumb'] = get_image_path($_REQUEST['goods_id'], $goods['goods_thumb'], true);
		}

		/* 图片列表 */
		$sql = "SELECT gg.*,c.color_name FROM " . $os->table('goods_gallery') . " gg LEFT JOIN " .
		$os->table('color') . " c ON gg.color_id=c.color_id WHERE gg.goods_id = '$goods[goods_id]' order by sort_order";
		$res = $db->query($sql);
		$img_list = array();
		while ($row = $db->fetchRow($res)){
			$row['option_param_desc'] = (!empty($row['color_name']) ? ($row['color_name'].'|') : '').($row['type']>1 ? '整体效果图' : '商品展示图');
			$row['img_original'] = $_CFG['pre_fetch_img'] . $row['img_original'];
			$img_list[] = $row;
		}

		/* 格式化相册图片路径 */
		if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 0))
		{
			foreach ($img_list as $key => $gallery_img)
			{
				$gallery_img[$key]['img_url'] = get_image_path($gallery_img['goods_id'], $gallery_img['img_original'], false, 'gallery');
				$gallery_img[$key]['thumb_url'] = get_image_path($gallery_img['goods_id'], $gallery_img['img_original'], true, 'gallery');
			}
		}
		else
		{
			foreach ($img_list as $key => $gallery_img)
			{
				$gallery_img[$key]['thumb_url'] = '../' . (empty($gallery_img['thumb_url']) ? $gallery_img['img_url'] : $gallery_img['thumb_url']);
			}
		}
	}

	if(!$is_add){
		$g_color_list = array();
		$sql = "SELECT gc.color_id,gc.goods_id,gc.color_name,gc.goods_color_id,cl.* FROM " . $os->table('goods_color') .
		" gc LEFT JOIN " . $os->table('color_lib') . " cl ON gc.img_id=cl.img_id " .
		" WHERE goods_id='$_REQUEST[goods_id]' ORDER BY goods_color_id ASC";

		//	 $sql = "SELECT gc.color_id ,gc.color_id ,gc.goods_id, gc.color_name,  gc.goods_color_id,oc.img_id,cl.img_name,cl.img_code,cl.img_file FROM " . $os->table('goods_color') .
		// 	     	" gc left join " . $os->table('color') . " oc  ON oc.color_id=gc.color_id " .
		//			" LEFT JOIN " . $os->table('color_lib') . " cl ON oc.img_id=cl.img_id " .
		//			" WHERE goods_id='$_REQUEST[goods_id]' ORDER BY goods_color_id ASC";


		//  echo $sql;
		$g_color_row = $db->getAll($sql);
		foreach ($g_color_row as $val) {
			$img_item = '';
			if(!empty($val['img_file']))
			$img_item = '<a href="'.$_CFG['pre_fetch_img'].$val['img_file'].'?16,16" target="_brank">
	                     <img src="'.$_CFG['pre_fetch_img'].$val['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$val['img_name'].'"/>
	                     </a>'; 
			$val['img_item'] = $img_item;
			$g_color_list[] = $val;
		}
		$smarty->assign('g_color_list',$g_color_list);

		$sql = "SELECT size_id, size_name, adjust_price FROM " . $os->table('goods_size') .
		" WHERE goods_id='$_REQUEST[goods_id]' ORDER BY goods_size_id ASC";
		$size_rows = $db->getAll($sql);
		$smarty->assign('size_list',$size_rows);

		$sql = "SELECT color_id, color_name FROM " . $os->table('goods_color') .
		" WHERE goods_id='$_REQUEST[goods_id]' ORDER BY goods_color_id DESC";
		$color_list = $db->getAll($sql);
		$smarty->assign('color_list', $color_list);

		$sql = "SELECT c.goods_type FROM " . $os->table('goods') ." g LEFT JOIN " .
		$os->table('category') ." c ON g.cat_id=c.cat_id WHERE g.goods_id='$_REQUEST[goods_id]' LIMIT 1";
		$goods['goods_type'] = $db->getOne($sql);
	}

	/* 拆分商品名称样式 */
	$goods_name_style = explode('+', empty($goods['goods_name_style']) ? '+' : $goods['goods_name_style']);
    $goods['depot_list'] = get_depots();
    $goods['seat_list'] = get_seats();
    
	/* 创建 html editor */
	create_html_editor('goods_desc', $goods['goods_desc']);

	/* 模板赋值 */
	$smarty->assign('code',    $code);
	$smarty->assign('ur_here', $is_add ? (empty($code) ? '添加新商品' : '添加新虚拟卡') : ($_REQUEST['act'] == 'edit' ? '编辑商品信息' : '复制商品信息'));
	$smarty->assign('action_link', list_link($is_add, $code));
	$smarty->assign('goods', $goods);
	$smarty->assign('goods_name_color', $goods_name_style[0]);
	$smarty->assign('goods_name_style', $goods_name_style[1]);
	$smarty->assign('cat_list', cat_list(0, $goods['cat_id']));
	$tmp_brands = get_brand_list();
	foreach($tmp_brands as $key => $value)
	{
		$brand['brand_id'] = $key;
		$brand['brand_name'] = $value;
		$brand_list[] = $brand;
	}
	$smarty->assign('brand_list', $brand_list);
	$smarty->assign('unit_list', get_unit_list());
	$smarty->assign('user_rank_list', get_user_rank_list());
	$smarty->assign('weight_unit', $is_add ? '1' : ($goods['goods_weight'] >= 1 ? '1' : '0.001'));
	$smarty->assign('cfg', $_CFG);
	$smarty->assign('form_act', $is_add ? 'insert' : ($_REQUEST['act'] == 'edit' ? 'update' : 'insert'));
	if ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
	{
		$smarty->assign('is_add', true);
	}
	if(!$is_add)
	{
		$smarty->assign('member_price_list', get_member_price_list($_REQUEST['goods_id']));
	}
	$smarty->assign('link_goods_list', $link_goods_list);
	$smarty->assign('group_goods_list', $group_goods_list);
	$smarty->assign('goods_article_list', $goods_article_list);
	$smarty->assign('img_list', $img_list);
	$smarty->assign('goods_type_list', goods_type_list($goods['goods_type']));
	$smarty->assign('gd', gd_version());
	$smarty->assign('thumb_width', $_CFG['thumb_width']);
	$smarty->assign('thumb_height', $_CFG['thumb_height']);
	$smarty->assign('goods_attr_html', build_attr_html($goods['goods_type'], $goods['goods_id']));
	$res = $db->query("SELECT lib_id,lib_name FROM ".$os->table('size_lib')." ORDER BY lib_id DESC");
	$size_lib_options = array();
	while ($row=$db->fetchRow($res)){
		$size_lib_options[$row['lib_id']] = $row['lib_name'];
	}
	$smarty->assign('size_lib_options',$size_lib_options);
	$volume_price_list = get_volume_price_list($_REQUEST['goods_id']);
	if (empty($volume_price_list))
	{
		$volume_price_list = array('0'=>array('number'=>'','price'=>''));
	}
	$smarty->assign('volume_price_list', $volume_price_list);

	$sql = 'select distinct storage_location from '.$os->table('goods').' order by storage_location asc';
	$s_location_list = $db->getAll($sql);

	$count = sizeof($s_location_list);

	if($count > 1){
		$smarty->assign('r_flag',1);
		$smarty->assign('storage_location_list',$s_location_list);
	}else{
		$smarty->assign('r_flag',0);
	}

	$sql = 'SELECT season_id,season_name FROM '.$os->table('season').' ORDER BY season_id ASC';
	$season_list = $db->getAll($sql);

	$sql = 'SELECT series_id,series_name FROM '.$os->table('series').' ORDER BY series_id ASC';
	$series_list = $db->getAll($sql);

	$smarty->assign('season_list',$season_list);
	$smarty->assign('series_list',$series_list);

	/* 显示商品信息页面 */
	assign_query_info();
	$smarty->display('goods_info.tpl');
}

elseif($_REQUEST['act']=='filter_seat_range'){
    if(!is_numeric($_GET['depot_id']))
    {
    	make_json_error('invalid param');
    	exit();
    } 	
    $result       = array('error'=>0, 'message'=>'', 'content'=>''); 
    $depot_id     = intval($_GET['depot_id']);

    $opt = array(); 
    
    if($depot_id>0){
	 	$arr          = get_seats($depot_id);	 	   
	    foreach ($arr AS $val)
	    {
	        $opt[] = array('value'      => $val['seat_id'],
	                        'text'      => $val['seat_name'],
	                        'data'      => '');
	    }
    }
        
    clear_cache_files();
    
    make_json_result($opt);     
}
/*------------------------------------------------------ */
//-- 插入商品 更新商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'insert' || $_REQUEST['act'] == 'update')
{
	//die( $_POST['goods_desc']);
	$code = empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);

	/* 是否处理缩略图 */
	$proc_thumb = (isset($GLOBALS['shop_id']) && $GLOBALS['shop_id'] > 0)? false : true;

	/* 插入还是更新的标识 */
	$is_insert = $_REQUEST['act'] == 'insert';
	$priv_str = $is_insert ? 'add_goods' : 'edit_goods';
	admin_priv($priv_str);

	/* 检查货号是否重复 */
	if ($_POST['goods_sn'])
	{
		$sql = "SELECT COUNT(*) FROM " . $os->table('goods') .
		" WHERE goods_sn = '$_POST[goods_sn]' AND is_delete = 0 AND goods_id <> '$_POST[goods_id]'";
		if ($db->getOne($sql) > 0)
		{
			sys_msg('您输入的货号已存在，请换一个', 1, array(), false);
		}
	}

	/* 处理商品图片 */
	$goods_img        = '';  // 初始化商品图片
	$goods_thumb      = '';  // 初始化商品缩略图
	$original_img     = '';  // 初始化原始图片
	$old_original_img = '';  // 初始化原始图片旧图

	// 如果上传了商品图片，相应处理
	if ($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none')
	{
		if ($_REQUEST['goods_id'] > 0)
		{
			/* 删除原来的图片文件 */
			$sql = "SELECT goods_id, goods_thumb, goods_img, original_img FROM " .
			$os->table('goods') . " WHERE goods_id = '$_REQUEST[goods_id]'";
			$row = $db->getRow($sql);

			if($filesync->sync_type != 'ftp'){
				if ($row['goods_thumb'] != '' && is_file(SOURCE_PATH . $row['goods_thumb']))
				{
					@unlink(SOURCE_PATH . $row['goods_thumb']);
				}
				if ($row['goods_img'] != '' && is_file(SOURCE_PATH . $row['goods_img']))
				{
					@unlink(SOURCE_PATH . $row['goods_img']);
				}
				if ($row['original_img'] != '' && is_file(SOURCE_PATH . $row['original_img']))
				{
					/* 先不处理，以防止程序中途出错停止 */
					//$old_original_img = $row['original_img']; //记录旧图路径
				}
				/* 清除原来商品图片 */
				if ($proc_thumb === false)
				{
					get_image_path($_REQUEST[goods_id], $row['goods_img'], false, 'goods', true);
					get_image_path($_REQUEST[goods_id], $row['goods_thumb'], true, 'goods', true);
				}
			}
		}

		if($filesync->sync_type=='ftp'){
			$filesync->connect();
			$filesync->setting('goods|img');
			$filesync->set_updata(!$is_insert, $_REQUEST['goods_id'], 'goods|img');
			$affix_data   =  $filesync->put_up($_FILES['goods_img']); // 原始图片

			$original_img   =  $affix_data['virtual_path'];
			$filesync->quit();
		}else{
			$original_img   = $filesync->upload_image($_FILES['goods_img']); // 原始图片
		}

		$goods_img      =  $original_img;

		if ($original_img===false || empty($original_img))
		{
			sys_msg('商品图片上传失败', 1, array(), false);
		}

		/* 添加判断是否自动生成相册图片 */
		if ($_CFG['auto_generate_gallery'])
		{
			if($filesync->sync_type=='ftp'){
				$filesync->connect();
				$filesync->setting('goods_gallery');
				$gallery_affix_data   = $filesync->put_up($_FILES['goods_img']); // 原始图片

				$img            = $gallery_affix_data['virtual_path'];
				$filesync->quit();
			}else{
				$img        = $original_img;   // 相册图片
				$pos        = strpos(basename($img), '.');
				$newname    = dirname($img) . '/' . $filesync->random_filename() . substr(basename($img), $pos);
				if (!copy(SOURCE_PATH . $img, SOURCE_PATH . $newname))
				{
					sys_msg('fail to copy file: ' . realpath(SOURCE_PATH . $img), 1, array(), false);
				}
				$img        = $newname;
			}

			$gallery_img    = $img;
			$gallery_thumb  = $img;
		}
	}

	// 是否上传商品缩略图
	if (isset($_FILES['goods_thumb']) && $_FILES['goods_thumb']['tmp_name'] != '' &&
	isset($_FILES['goods_thumb']['tmp_name']) &&$_FILES['goods_thumb']['tmp_name'] != 'none')
	{
		// 上传了，直接使用，原始大小
		if($filesync->sync_type=='ftp'){
			$filesync->connect();
			$filesync->setting('goods|thumb');
			$filesync->set_updata(!$is_insert, $_REQUEST['goods_id'], 'goods|thumb');
			$affix_thumb_data   = $filesync->put_up($_FILES['goods_thumb']); // 原始图片
			$goods_thumb = $affix_thumb_data['virtual_path'];
			$filesync->quit();
		}else{
			$goods_thumb = $filesync->upload_image($_FILES['goods_thumb']);
		}
		if ($goods_thumb===false || empty($goods_thumb))
		{
			sys_msg('商品缩略图上传失败', 1, array(), false);
		}
	}else{
		$goods_thumb = $original_img;
	}

	/* 如果没有输入商品货号则自动生成一个商品货号 */
	if (empty($_POST['goods_sn']))
	{
		$max_id     = $is_insert ? $db->getOne("SELECT MAX(goods_id) + 1 FROM ".$os->table('goods')) : $_REQUEST['goods_id'];
		$goods_sn   = generate_goods_sn($max_id);
	}
	else
	{
		$goods_sn   = $_POST['goods_sn'];
	}

	/* 处理商品数据 */
	$shop_price = !empty($_POST['shop_price']) ? $_POST['shop_price'] : 0;
	$market_price = !empty($_POST['market_price']) ? $_POST['market_price'] : 0;
	$promote_price = !empty($_POST['promote_price']) ? floatval($_POST['promote_price'] ) : 0;
	$is_promote = empty($promote_price) ? 0 : 1;
	$promote_start_date = ($is_promote && !empty($_POST['promote_start_date'])) ? local_strtotime($_POST['promote_start_date']) : 0;
	$promote_end_date = ($is_promote && !empty($_POST['promote_end_date'])) ? local_strtotime($_POST['promote_end_date']) : 0;
	$goods_weight = !empty($_POST['goods_weight']) ? $_POST['goods_weight'] * $_POST['weight_unit'] : 0;
	$is_best = isset($_POST['is_best']) ? 1 : 0;
	$is_new = isset($_POST['is_new']) ? 1 : 0;
	$is_hot = isset($_POST['is_hot']) ? 1 : 0;
	$is_presale = isset($_POST['is_presale']) ? 1 : 0;
	$is_on_sale = isset($_POST['is_on_sale']) ? 1 : 0;
	$is_alone_sale = isset($_POST['is_alone_sale']) ? 1 : 0;
	$goods_number = isset($_POST['goods_number']) ? $_POST['goods_number'] : 0;
	$warn_number = isset($_POST['warn_number']) ? $_POST['warn_number'] : 0;
	$goods_type = isset($_POST['goods_type']) ? $_POST['goods_type'] : 0;
	$give_integral = isset($_POST['give_integral']) ? intval($_POST['give_integral']) : '-1';
	$rank_integral = isset($_POST['rank_integral']) ? intval($_POST['rank_integral']) : '-1';

	$storage_location = trim($_POST['storage_location']);

	$goods_name_style = $_POST['goods_name_color'] . '+' . $_POST['goods_name_style'];
	$catgory_id = empty($_POST['cat_id']) ? '' : intval($_POST['cat_id']);
	$brand_id = empty($_POST['brand_id']) ? '' : intval($_POST['brand_id']);

	$goods_img = (empty($goods_img) && !empty($_POST['goods_img_url']) && goods_parse_url($_POST['goods_img_url'])) ? htmlspecialchars(trim($_POST['goods_img_url'])) : $goods_img;
	$goods_thumb = (empty($goods_thumb) && !empty($_POST['goods_thumb_url']) && goods_parse_url($_POST['goods_thumb_url'])) ? htmlspecialchars(trim($_POST['goods_thumb_url'])) : $goods_thumb;
	$goods_thumb = (empty($goods_thumb) && isset($_POST['auto_thumb']))? $goods_img : $goods_thumb;
	$size_lib_id = empty($_POST['size_lib_id']) ? 0 : intval($_POST['size_lib_id']);

	$sales_type = empty($_POST['sales_type']) ? 1 : intval($_POST['sales_type']);
	$season_id  = empty($_POST['season_id']) ? 0 : intval($_POST['season_id']);
	$series_id  = empty($_POST['series_id']) ? 0 : intval($_POST['series_id']);
	$depot_id   = empty($_POST['depot_id']) ? 0 : intval($_POST['depot_id']);
	$seat_id    = empty($_POST['seat_id']) ? 0 : intval($_POST['seat_id']);

	/* 入库 */
	if ($is_insert)
	{
		if ($code == '')
		{
			$sql = "INSERT INTO " . $os->table('goods') . " (goods_name, goods_name_style, goods_sn, " .
			"cat_id, brand_id, shop_price, market_price, is_promote, promote_price, " .
			"promote_start_date, promote_end_date, goods_img, goods_thumb, original_img, keywords, goods_brief, " .
			"seller_note, goods_weight, goods_number, warn_number, integral, give_integral, is_best, is_new, is_hot, " .
			"is_presale, is_on_sale, is_alone_sale, goods_desc, add_time, last_update, goods_type, rank_integral, " . 
			" size_lib_id, storage_location, season_id, series_id, depot_id, seat_id, sales_type)" .
			"VALUES ('$_POST[goods_name]', '$goods_name_style', '$goods_sn', '$catgory_id', " .
			"'$brand_id', '$shop_price', '$market_price', '$is_promote','$promote_price', " .
			"'$promote_start_date', '$promote_end_date', '$goods_img', '$goods_thumb', '$original_img', " . 
			"'$_POST[keywords]', '$_POST[goods_brief]', '$_POST[seller_note]', '$goods_weight', '$goods_number', " . 
			" '$warn_number', '$_POST[integral]', '$give_integral', '$is_best', '$is_new', '$is_hot', " . 
			" '$is_presale', '$is_on_sale', '$is_alone_sale', '$_POST[goods_desc]', '" . gmtime() . "', '" .  
			gmtime() ."', '$goods_type', '$rank_integral', '$size_lib_id', '$storage_location','$season_id'," . 
			" '$series_id', '$depot_id', '$seat_id', '$sales_type')";
		}
		else
		{
			$sql = "INSERT INTO " . $os->table('goods') . " (goods_name, goods_name_style, goods_sn, " .
			"cat_id, brand_id, shop_price, market_price, is_promote, promote_price, " .
			"promote_start_date, promote_end_date, goods_img, goods_thumb, original_img, keywords, goods_brief, " .
			"seller_note, goods_weight, goods_number, warn_number, integral, give_integral, is_best, is_new, is_hot, " .
			"is_presale, is_real, is_on_sale, is_alone_sale, goods_desc, add_time, last_update, goods_type, " .
			"extension_code, rank_integral, size_lib_id, storage_location, season_id, series_id, depot_id, seat_id)" .
			"VALUES ('$_POST[goods_name]', '$goods_name_style', '$goods_sn', '$catgory_id', " .
			"'$brand_id', '$shop_price', '$market_price', '$is_promote','$promote_price', ".
			"'$promote_start_date', '$promote_end_date', '$goods_img', '$goods_thumb', '$original_img', ".
			"'$_POST[keywords]', '$_POST[goods_brief]', '$_POST[seller_note]', '$goods_weight', '$goods_number', ".
			" '$warn_number', '$_POST[integral]', '$give_integral', '$is_best', '$is_new', '$is_hot', ".
			" '$is_presale', 0, '$is_on_sale', '$is_alone_sale', '$_POST[goods_desc]', '" . gmtime() . "', '". gmtime() .
			"', '$goods_type', '$code', '$rank_integral', '$size_lib_id', '$storage_location', '$season_id', '$series_id', '$depot_id', '$seat_id')";
		}
	}
	else
	{
		$sql = "UPDATE " . $os->table('goods') . " SET " .
		"goods_name = '$_POST[goods_name]', " .
		"goods_name_style = '$goods_name_style', " .
		"goods_sn = '$goods_sn', " .
		"storage_location = '$storage_location', " .
		"season_id = '$season_id', " .
		"series_id = '$series_id', " .
		"depot_id  = '$depot_id', " .
		"seat_id   = '$seat_id', " .		
		"sales_type = '$sales_type', " .
		"cat_id = '$catgory_id', " .
		"brand_id = '$brand_id', " .
		"shop_price = '$shop_price', " .
		"market_price = '$market_price', " .
		"is_promote = '$is_promote', " .
		"promote_price = '$promote_price', " .
		"promote_start_date = '$promote_start_date', " .
		"promote_end_date = '$promote_end_date', ";

		/* 如果有上传图片，需要更新数据库 */
		if ($original_img)
		{
			$sql .= "goods_img = '$goods_img', original_img = '$original_img', ";
		}
		if ($goods_thumb)
		{
			$sql .= "goods_thumb = '$goods_thumb', ";
		}
		if ($code != '')
		{
			$sql .= "is_real=0, extension_code='$code', ";
		}
		$sql .= "keywords = '$_POST[keywords]', " .
		"goods_brief = '$_POST[goods_brief]', " .
		"seller_note = '$_POST[seller_note]', " .
		"goods_weight = '$goods_weight'," .
		"goods_number = '$goods_number', " .
		"warn_number = '$warn_number', " .
		"integral = '$_POST[integral]', " .
		"give_integral = '$give_integral', " .
		"rank_integral = '$rank_integral', " .
		"size_lib_id = '$size_lib_id', " .
		"is_best = '$is_best', " .
		"is_new = '$is_new', " .
		"is_hot = '$is_hot', " .
		"is_presale = '$is_presale', " .
		"is_on_sale = '$is_on_sale', " .
		"is_alone_sale = '$is_alone_sale', " .
		"goods_desc = '$_POST[goods_desc]', " .
		"last_update = '". gmtime() ."', ".
		"goods_type = '$goods_type' " .
		"WHERE goods_id = '$_REQUEST[goods_id]' LIMIT 1";
	}

	$db->query($sql);

	/* 商品编号 */
	$goods_id = $is_insert ? $db->insert_id() : $_REQUEST['goods_id'];

	/* 记录日志 */
	if ($is_insert)
	{
		admin_log($_POST['goods_name'], 'add', 'goods');
	}
	else
	{
		admin_log($_POST['goods_name'], 'edit', 'goods');
	}

	/* 处理规格 */
	if(!$is_insert){
		$db->query("DELETE FROM " . $os->table('goods_size') . " WHERE goods_id='$goods_id'");
	}
	for($j=0;$j<sizeof($_POST['size_ids_value']);$j++){
		$size_id = intval($_POST['size_ids_value'][$j]);
		$size_price = intval($_POST['size_price'][$j]);
		$size_name = $db->getOne("SELECT size_name FROM " . $os->table('size') . " WHERE size_id='$size_id'");
		$sql = "INSERT INTO " . $os->table('goods_size') . " VALUES(null,'$goods_id','$size_id',
	       '$size_name','$size_price','','')";
		$db->query($sql);
	}
	/* 处理属性 */
	if (isset($_POST['attr_id_list']) && isset($_POST['attr_value_list']))
	{
		// 取得原有的属性值
		$goods_attr_list = array();

		$keywords_arr = explode(" ", $_POST['keywords']);

		$keywords_arr = array_flip($keywords_arr);
		if (isset($keywords_arr['']))
		{
			unset($keywords_arr['']);
		}

		$sql = "SELECT attr_id, attr_index FROM " . $os->table('attribute') . " WHERE cat_id = '$goods_type'";

		$attr_res = $db->query($sql);

		$attr_list = array();

		while ($row = $db->fetchRow($attr_res))
		{
			$attr_list[$row['attr_id']] = $row['attr_index'];
		}

		$sql = "SELECT * FROM " . $os->table('goods_attr') . " WHERE goods_id = '$goods_id'";

		$res = $db->query($sql);

		while ($row = $db->fetchRow($res))
		{
			$goods_attr_list[$row['attr_id']][$row['attr_value']] = array('sign' => 'delete', 'goods_attr_id' => $row['goods_attr_id']);
		}


		// 循环现有的，根据原有的做相应处理
		foreach ($_POST['attr_id_list'] AS $key => $attr_id)
		{
			$attr_value = $_POST['attr_value_list'][$key];
			$attr_price = $_POST['attr_price_list'][$key];

			if (!empty($attr_value))
			{

				if (isset($goods_attr_list[$attr_id][$attr_value]))
				{
					// 如果原来有，标记为更新
					$goods_attr_list[$attr_id][$attr_value]['sign'] = 'update';
					$goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
				}
				else
				{
					// 如果原来没有，标记为新增
					$goods_attr_list[$attr_id][$attr_value]['sign'] = 'insert';
					$goods_attr_list[$attr_id][$attr_value]['attr_price'] = $attr_price;
				}

				$val_arr = explode(' ', $attr_value);

				foreach ($val_arr AS $k => $v)
				{
					if (!isset($keywords_arr[$v]) && $attr_list[$attr_id] == "1")
					{
						$keywords_arr[$v] = $v;
					}
				}
			}
		}

		$keywords = join(' ', array_flip($keywords_arr));

		$sql = "UPDATE " .$os->table('goods'). " SET keywords = '$keywords' WHERE goods_id = '$goods_id' LIMIT 1";

		$db->query($sql);

		/* 插入、更新、删除数据 */
		foreach ($goods_attr_list as $attr_id => $attr_value_list)
		{
			foreach ($attr_value_list as $attr_value => $info)
			{
				if ($info['sign'] == 'insert')
				{
					$sql = "INSERT INTO " .$os->table('goods_attr'). " (attr_id, goods_id, attr_value, attr_price)".
					"VALUES ('$attr_id', '$goods_id', '$attr_value', '$info[attr_price]')";
				}
				elseif ($info['sign'] == 'update')
				{
					$sql = "UPDATE " .$os->table('goods_attr'). " SET attr_price = '$info[attr_price]' WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1";
				}
				else
				{
					$sql = "DELETE FROM " .$os->table('goods_attr'). " WHERE goods_attr_id = '$info[goods_attr_id]' LIMIT 1";
				}
				$db->query($sql);
			}
		}
	}

	/* 处理客户价格 */
	if (isset($_POST['user_rank']) && isset($_POST['user_price']))
	{
		handle_member_price($goods_id, $_POST['user_rank'], $_POST['user_price']);
	}

	/* 处理优惠价格 */
	if (isset($_POST['volume_number']) && isset($_POST['volume_price']))
	{
		$temp_num = array_count_values($_POST['volume_number']);
		foreach($temp_num as $v)
		{
			if ($v > 1)
			{
				sys_msg('优惠数量重复！', 1, array(), false);
				break;
			}
		}

		handle_volume_price($goods_id, $_POST['volume_number'], $_POST['volume_price']);
	}

	/* 处理扩展分类 */
	if (isset($_POST['other_cat']))
	{
		handle_other_cat($goods_id, array_unique($_POST['other_cat']));
	}

	if ($is_insert)
	{
		/* 处理关联商品 */
		handle_link_goods($goods_id);

		/* 处理组合商品 */
		handle_group_goods($goods_id);

		/* 处理关联文章 */
		handle_goods_article($goods_id);
	}

	if($filesync->sync_type!='ftp'){
		/* 重新格式化图片名称 */
		$original_img = reformat_image_name('goods', $goods_id, $original_img);
		$goods_img = $original_img;
		$goods_thumb = $original_img;
		if ($goods_img !== false)
		{
			$db->query("UPDATE " . $os->table('goods') . " SET goods_img = '$goods_img' WHERE goods_id='$goods_id'");
		}

		if ($original_img !== false)
		{
			$db->query("UPDATE " . $os->table('goods') . " SET original_img = '$original_img' WHERE goods_id='$goods_id'");
		}

		if ($goods_thumb !== false)
		{
			$db->query("UPDATE " . $os->table('goods') . " SET goods_thumb = '$goods_thumb' WHERE goods_id='$goods_id'");
		}
	}

	/* 如果有图片，把商品图片加入图片相册 */
	if (isset($img))
	{
		if($filesync->sync_type!='ftp'){
			/* 重新格式化图片名称 */
			$img = reformat_image_name('gallery', $goods_id, $img);
			$gallery_img = $img;
			$gallery_thumb = $img;
		}
		$sql = "INSERT INTO " . $os->table('goods_gallery') . " (goods_id, img_url, img_desc, thumb_url, img_original) " .
		"VALUES ('$goods_id', '$gallery_img', '', '$gallery_thumb', '$img')";
		$db->query($sql);
	}
	/* 处理相册图片 */
	handle_gallery_image($goods_id, $_FILES['img_url'], $_POST['img_desc']);

	/* 编辑时处理相册图片描述 */
	if (!$is_insert && isset($_POST['old_img_desc']))
	{
		foreach ($_POST['old_img_desc'] AS $img_id => $img_desc)
		{
			$sql = "UPDATE " . $os->table('goods_gallery') . " SET img_desc = '$img_desc',sort_order = ".$_POST['old_sort_order'][$img_id]." WHERE img_id = '$img_id' LIMIT 1";
			$db->query($sql);
		}
	}

	/* 不保留商品原图的时候删除原图 */
	//    if ($proc_thumb && !$_CFG['retain_original_img'] && !empty($original_img))
	//    {
	//        $db->query("UPDATE " . $os->table('goods') . " SET original_img='' WHERE `goods_id`='{$goods_id}'");
	//        @unlink(SOURCE_PATH . $original_img);
	//    }

	/* 记录上一次选择的分类和品牌 */
	setcookie('OSCP[last_choose]', $catgory_id . '|' . $brand_id, gmtime() + 86400);
	/* 清空缓存 */
	clear_cache_files();

	if($_REQUEST['act'] == 'insert'){
		$go_url = "goods.php?act=edit&goods_id=". $goods_id;
		echo "<meta http-equiv=refresh content='0; url=".$go_url."'>";
	}
	else
	{
		/* 提示页面 */
		$link = array();
		$link[] = array('href' => 'goods.php?act=edit&goods_id=' . $goods_id, 'text' => '继续编辑商品');
		if ($code == 'virtual_card')
		{
			$link[] = array('href' => 'virtual_card.php?act=replenish&goods_id=' . $goods_id, 'text' => '添加虚拟卡卡密');
		}
		if ($is_insert)
		{
			$link[] = add_link($code);
		}
		$link[] = list_link($is_insert, $code);
		$link[0]['href'] = 'goods.php?act=edit&goods_id='.$_POST['goods_id'].'&extension_code='.$code;
		sys_msg($is_insert ? '添加商品成功' : '商品编辑成功', 0, $link);
	}
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch')
{
	$code = empty($_REQUEST['extension_code'])? '' : trim($_REQUEST['extension_code']);

	/* 取得要操作的商品编号 */
	$goods_id = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;

	if (isset($_POST['type']))
	{
		/* 放入回收站 */
		if ($_POST['type'] == 'trash')
		{
			/* 检查权限 */
			admin_priv('trash_goods');

			update_goods($goods_id, 'is_delete', '1');

			/* 记录日志 */
			admin_log('', 'batch_trash', 'goods');
		}
		/* 上架 */
		elseif ($_POST['type'] == 'on_sale')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_on_sale', '1');
		}

		/* 下架 */
		elseif ($_POST['type'] == 'not_on_sale')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_on_sale', '0');
		}

		/* 设为精品 */
		elseif ($_POST['type'] == 'best')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_best', '1');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 取消精品 */
		elseif ($_POST['type'] == 'not_best')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_best', '0');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 设为新品 */
		elseif ($_POST['type'] == 'new')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_new', '1');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 取消新品 */
		elseif ($_POST['type'] == 'not_new')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_new', '0');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 设为热销 */
		elseif ($_POST['type'] == 'hot')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_hot', '1');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 取消热销 */
		elseif ($_POST['type'] == 'not_hot')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_hot', '0');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 设为预售 */
		elseif ($_POST['type'] == 'presale')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_presale', '1');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 取消预售 */
		elseif ($_POST['type'] == 'not_presale')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'is_presale', '0');
			if ($_CFG['use_promise_delivery']) { update_goods_shipping_days(explode(',', $goods_id)); }
		}

		/* 转移到分类 */
		elseif ($_POST['type'] == 'move_to')
		{
			/* 检查权限 */
			admin_priv('edit_goods');
			update_goods($goods_id, 'cat_id', $_POST['target_cat']);
		}
		/* 还原 */
		elseif ($_POST['type'] == 'restore')
		{
			/* 检查权限 */
			admin_priv('restore_goods');

			update_goods($goods_id, 'is_delete', '0');

			/* 记录日志 */
			admin_log('', 'batch_restore', 'goods');
		}
		/* 删除 */
		elseif ($_POST['type'] == 'drop')
		{
			/* 检查权限 */
			admin_priv('drop_goods');

			delete_goods($goods_id);

			/* 记录日志 */
			admin_log('', 'batch_remove', 'goods');
		}
	}

	/* 清除缓存 */
	clear_cache_files();

	if ($_POST['type'] == 'drop' || $_POST['type'] == 'restore')
	{
		$link[] = array('href' => 'goods.php?act=trash', 'text' => '商品回收站');
	}
	else
	{
		$link[] = list_link(true, $code);
	}
	sys_msg('批量操作成功。', 0, $link);
}

/*------------------------------------------------------ */
//-- 显示图片
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'show_image')
{
	if (isset($GLOBALS['shop_id']) && $GLOBALS['shop_id'] > 0)
	{
		$img_url = $_GET['img_url'];
	}
	else
	{
		if (strpos($_GET['img_url'], 'http://') === 0)
		{
			$img_url = $_GET['img_url'];
		}
		else
		{
			$img_url = '' . $_GET['img_url'];
		}
	}

	$img_url= $_CFG['pre_fetch_img'] .  $img_url ;

	$smarty->assign('img_url', $img_url);

	$smarty->display('goods_show_image.tpl');
}

/*------------------------------------------------------ */
//-- 修改商品名称
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_name')
{

	check_authz_json('edit_goods');

	$goods_id   = intval($_POST['id']);

	$goods_name = json_str_iconv(trim($_POST['val']));


	if ($exc->edit("goods_name = '$goods_name', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result(stripslashes($goods_name));
	}
}

/*------------------------------------------------------ */
//-- 修改商品货号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_sn')
{
	check_authz_json('edit_goods');

	$goods_id = intval($_POST['id']);
	$goods_sn = json_str_iconv(trim($_POST['val']));

	/* 检查是否重复 */
	if (!$exc->is_only('goods_sn', $goods_sn, $goods_id))
	{
		make_json_error('您输入的货号已存在，请换一个');
	}

	if ($exc->edit("goods_sn = '$goods_sn', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result(stripslashes($goods_sn));
	}
}

elseif ($_REQUEST['act'] == 'check_goods_sn')
{
	check_authz_json('edit_goods');

	$goods_id = intval($_REQUEST['goods_id']);
	$goods_sn = json_str_iconv(trim($_REQUEST['goods_sn']));

	/* 检查是否重复 */
	if (!$exc->is_only('goods_sn', $goods_sn, $goods_id))
	{
		make_json_error('您输入的货号已存在，请换一个');
	}

	make_json_result('');
}
/*------------------------------------------------------ */
//-- 修改商品价格
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_price')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$goods_price    = floatval($_POST['val']);

	if ($goods_price < 0 || $goods_price == 0 && $_POST['val'] != "$goods_price")
	{
		make_json_error('您输入了一个非法的市场价格。');
	}
	else
	{
		if ($exc->edit("shop_price = '$goods_price', last_update=" .gmtime(), $goods_id))
		{
			clear_cache_files();
			make_json_result(number_format($goods_price, 2, '.', ''));
		}
	}
}

/*------------------------------------------------------ */
//-- 修改商品库存数量
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_goods_number')
{
	check_authz_json('edit_goods');

	$goods_id   = intval($_POST['id']);
	$goods_num  = intval($_POST['val']);

	if($goods_num < 0 || $goods_num == 0 && $_POST['val'] != "$goods_num")
	{
		make_json_error('商品库存数量错误');
	}

	if ($exc->edit("goods_number = '$goods_num', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result($goods_num);
	}
}

/*------------------------------------------------------ */
//-- 修改上架状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_on_sale')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$on_sale        = intval($_POST['val']);

	if ($exc->edit("is_on_sale = '$on_sale', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result($on_sale);
	}
}

/*------------------------------------------------------ */
//-- 修改精品推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_best')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$is_best        = intval($_POST['val']);

	if ($exc->edit("is_best = '$is_best', last_update=" .gmtime(), $goods_id))
	{
		if ($_CFG['use_promise_delivery']) { update_good_shipping_days($goods_id); }
		clear_cache_files();
		make_json_result($is_best);
	}
}

/*------------------------------------------------------ */
//-- 修改新品推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_new')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$is_new         = intval($_POST['val']);

	if ($exc->edit("is_new = '$is_new', last_update=" .gmtime(), $goods_id))
	{
		if ($_CFG['use_promise_delivery']) { update_good_shipping_days($goods_id); }
		clear_cache_files();
		make_json_result($is_new);
	}
}

/*------------------------------------------------------ */
//-- 修改热销推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_hot')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$is_hot         = intval($_POST['val']);

	if ($exc->edit("is_hot = '$is_hot', last_update=" .gmtime(), $goods_id))
	{
		if ($_CFG['use_promise_delivery']) { update_good_shipping_days($goods_id); }
		clear_cache_files();
		make_json_result($is_hot);
	}
}

/*------------------------------------------------------ */
//-- 修改预售推荐状态
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'toggle_presale')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$is_presale     = intval($_POST['val']);

	if ($exc->edit("is_presale = '$is_presale', last_update=" .gmtime(), $goods_id))
	{
		if ($_CFG['use_promise_delivery']) { update_good_shipping_days($goods_id); }
		clear_cache_files();
		make_json_result($is_presale);
	}
}

/*------------------------------------------------------ */
//-- 修改商品承诺发货天数
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_shipping_days')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$shipping_days  = intval($_POST['val']);

	if ($exc->edit("shipping_days = '$shipping_days', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result($shipping_days);
	}
}

/*------------------------------------------------------ */
//-- 修改热销统计天数
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_statistic_days')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$statistic_days = intval($_POST['val']);

	if ($exc->edit("statistic_days = '$statistic_days', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result($statistic_days);
	}
}

/*------------------------------------------------------ */
//-- 修改热销日均销售量
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_hot_number')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$hot_number     = intval($_POST['val']);

	if ($exc->edit("hot_number = '$hot_number', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result($hot_number);
	}
}

/*------------------------------------------------------ */
//-- 修改商品排序
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_sort_order')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$sort_order     = intval($_POST['val']);

	if ($exc->edit("sort_order = '$sort_order', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result($sort_order);
	}
}

// 添加商品库位操作
elseif ($_REQUEST['act'] == 'edit_storage_location')
{
	check_authz_json('edit_goods');

	$goods_id       = intval($_POST['id']);
	$storage_location     = trim($_POST['val']);

	if ($exc->edit("storage_location = '$storage_location', last_update=" .gmtime(), $goods_id))
	{
		clear_cache_files();
		make_json_result($storage_location);
	}
}
// 结束修改


/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
	$is_delete = empty($_REQUEST['is_delete']) ? 0 : intval($_REQUEST['is_delete']);
	$code = empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
	$goods_list = goods_list($is_delete, ($code=='') ? 1 : 0);

	//    $new_file = fopen("d:/log.txt","rw");
	//    fwrite($new_file,$goods_list);
	//    fclose($new_file);

	$handler_list = array();
	$handler_list['virtual_card'][] = array('url'=>'virtual_card.php?act=card', 'title'=>'查看虚拟卡信息', 'img'=>'icon_send_bonus.gif');
	$handler_list['virtual_card'][] = array('url'=>'virtual_card.php?act=replenish', 'title'=>'补货', 'img'=>'icon_add.gif');
	$handler_list['virtual_card'][] = array('url'=>'virtual_card.php?act=batch_card_add', 'title'=>'批量补货', 'img'=>'icon_output.gif');

	if (isset($handler_list[$code]))
	{
		$smarty->assign('add_handler',      $handler_list[$code]);
	}

	$smarty->assign('goods_list',   $goods_list['goods']);
	$smarty->assign('filter',       $goods_list['filter']);
	$smarty->assign('record_count', $goods_list['record_count']);
	$smarty->assign('page_count',   $goods_list['page_count']);
	$smarty->assign('list_type',    $is_delete ? 'trash' : 'goods');
	$smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);

	/* 排序标记 */
	$sort_flag  = sort_flag($goods_list['filter']);
	$smarty->assign($sort_flag['tag'], $sort_flag['img']);

	$tpl = $is_delete ? 'goods_trash.tpl' : 'goods_list.tpl';

	make_json_result($smarty->fetch($tpl), '',
	array('filter' => $goods_list['filter'], 'page_count' => $goods_list['page_count']));
}

/*------------------------------------------------------ */
//-- 放入回收站
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove')
{
	$goods_id = intval($_REQUEST['id']);

	/* 检查权限 */
	check_authz_json('trash_goods');

	if ($exc->edit("is_delete = 1", $goods_id))
	{
		clear_cache_files();
		$goods_name = $exc->get_name($goods_id);

		admin_log(addslashes($goods_name), 'trash', 'goods'); // 记录日志

		$url = 'goods.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

		os_header("Location: $url\n");
		exit;
	}
}

/*------------------------------------------------------ */
//-- 还原回收站中的商品
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'restore_goods')
{
	$goods_id = intval($_REQUEST['id']);

	check_authz_json('restore_goods'); // 检查权限

	$exc->edit("is_delete = 0, add_time = '" . gmtime() . "'", $goods_id);
	clear_cache_files();

	$goods_name = $exc->get_name($goods_id);

	admin_log(addslashes($goods_name), 'restore', 'goods'); // 记录日志

	$url = 'goods.php?act=query&' . str_replace('act=restore_goods', '', $_SERVER['QUERY_STRING']);

	os_header("Location: $url\n");
	exit;
}

/*------------------------------------------------------ */
//-- 彻底删除商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_goods')
{
	// 检查权限
	check_authz_json('drop_goods');

	// 取得参数
	$goods_id = intval($_REQUEST['id']);
	if ($goods_id <= 0)
	{
		make_json_error('invalid params');
	}

	/* 取得商品信息 */
	$sql = "SELECT goods_id, goods_name, is_delete, is_real, goods_thumb, " .
	"goods_img, original_img " .
	"FROM " . $os->table('goods') .
	" WHERE goods_id = '$goods_id'";
	$goods = $db->getRow($sql);
	if (empty($goods))
	{
		make_json_error('该商品不存在');
	}

	if ($goods['is_delete'] != 1)
	{
		make_json_error('该商品尚未放入回收站，不能删除');
	}

	/* 删除商品图片和轮播图片 */
	if($filesync->sync_type=='ftp'){
		$filesync->connect();
		@$filesync->drop($goods['goods_id'], 'goods|img');
		$filesync->quit();

		$filesync->connect();
		@$filesync->drop($goods['goods_id'], 'goods|thumb');
		$filesync->quit();
	}else{
		if (!empty($goods['goods_thumb']))
		{
			@unlink(SOURCE_PATH . $goods['goods_thumb']);
		}
		if (!empty($goods['goods_img']))
		{
			@unlink(SOURCE_PATH . $goods['goods_img']);
		}
		if (!empty($goods['original_img']))
		{
			@unlink(SOURCE_PATH . $goods['original_img']);
		}
	}

	/* 删除商品 */
	$exc->drop($goods_id);

	/* 记录日志 */
	admin_log(addslashes($goods['goods_name']), 'remove', 'goods');

	/* 删除商品相册 */
	$sql = "SELECT img_id, img_url, thumb_url, img_original " .
	"FROM " . $os->table('goods_gallery') .
	" WHERE goods_id = '$goods_id'";
	$res = $db->query($sql);
	while ($row = $db->fetchRow($res))
	{
		if($filesync->sync_type=='ftp'){
			$filesync->connect();
			@$filesync->drop($row['img_id'], 'goods_gallery');
			$filesync->quit();
		}else{
			if (!empty($row['img_url']))
			{
				@unlink(SOURCE_PATH . $row['img_url']);
			}
			if (!empty($row['thumb_url']))
			{
				@unlink(SOURCE_PATH . $row['thumb_url']);
			}
			if (!empty($row['img_original']))
			{
				@unlink(SOURCE_PATH . $row['img_original']);
			}
		}
	}

	$sql = "DELETE FROM " . $os->table('goods_gallery') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);

	/* 删除相关表记录 */
	$sql = "DELETE FROM " . $os->table('collect_goods') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('goods_article') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('goods_attr') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('goods_cat') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('member_price') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('group_goods') . " WHERE parent_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('group_goods') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('link_goods') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('link_goods') . " WHERE link_goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('tag') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('comment') . " WHERE comment_type = 0 AND id_value = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('collect_goods') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('booking_goods') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	$sql = "DELETE FROM " . $os->table('goods_activity') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);

	// 删除相关库存表记录
	$sql = "DELETE FROM " . $os->table('goods_inventory') . " WHERE goods_id = '$goods_id'";
	$db->query($sql);
	// END 添加

	/* 如果不是实体商品，删除相应虚拟商品记录 */
	if ($goods['is_real'] != 1)
	{
		$sql = "DELETE FROM " . $os->table('virtual_card') . " WHERE goods_id = '$goods_id'";
		if (!$db->query($sql, 'SILENT') && $db->errno() != 1146)
		{
			die($db->error());
		}
	}

	clear_cache_files();
	$url = 'goods.php?act=query&' . str_replace('act=drop_goods', '', $_SERVER['QUERY_STRING']);

	os_header("Location: $url\n");

	exit;
}

/*------------------------------------------------------ */
//-- 切换商品类型
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_attr')
{
	check_authz_json('edit_goods');

	$goods_id   = empty($_GET['goods_id']) ? 0 : intval($_GET['goods_id']);
	$cat_id = empty($_GET['cat_id']) ? 0 : intval($_GET['cat_id']);

	$sql = "SELECT goods_type FROM " . $os->table('category') ." WHERE cat_id='$cat_id' LIMIT 1";
	$goods_type = $db->getOne($sql);
	$content    = build_attr_html($goods_type, $goods_id);

	make_json_result($content);
}

/*------------------------------------------------------ */
//-- 删除图片
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_image')
{
	check_authz_json('drop_goods');

	$img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);

	/* 删除图片文件 */
	$sql = "SELECT img_url, thumb_url, img_original " .
	" FROM " . $GLOBALS['os']->table('goods_gallery') .
	" WHERE img_id = '$img_id'";
	$row = $GLOBALS['db']->getRow($sql);

	/*××××××××××××××××××××××××××暂时不删除图片×××××××××××××××××××××××××××××××××××××××××
	if($filesync->sync_type=='ftp'){
	$filesync->connect();
	@$filesync->drop($img_id, 'goods_gallery');
	$filesync->quit();
	}else{
	if ($row['img_url'] != '' && is_file(SOURCE_PATH . $row['img_url']))
	{
	@unlink(SOURCE_PATH . $row['img_url']);
	}
	if ($row['thumb_url'] != '' && is_file(SOURCE_PATH . $row['thumb_url']))
	{
	@unlink(SOURCE_PATH . $row['thumb_url']);
	}
	if ($row['img_original'] != '' && is_file(SOURCE_PATH . $row['img_original']))
	{
	@unlink(SOURCE_PATH . $row['img_original']);
	}
	}
	*/

	/* 删除数据 */
	$sql = "DELETE FROM " . $GLOBALS['os']->table('goods_gallery') . " WHERE img_id = '$img_id' LIMIT 1";
	$GLOBALS['db']->query($sql);

	clear_cache_files();
	make_json_result($img_id);
}

elseif($_REQUEST['act']=='change_goods_img'){
	//check_authz_json('edit_goods');
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;
	$img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);
	$goods_id = empty($_REQUEST['g_id']) ? 0 : intval($_REQUEST['g_id']);
	$img_original = $db->getOne("SELECT img_original FROM " . $os->table('goods_gallery') . " WHERE img_id=$img_id");
	$sql = "UPDATE " . $os->table('goods') . " SET goods_thumb='$img_original',goods_img='$img_original',original_img='$img_original' WHERE goods_id = '$goods_id' LIMIT 1";
	$db->query($sql);
	clear_cache_files();
	make_json_result('change_yes');
}

/*------------------------------------------------------ */
//-- 搜索商品，仅返回名称及ID
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_goods_list')
{
	check_authz_json('edit_goods');
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$filters = $json->decode($_GET['JSON']);

	$arr = get_goods_list($filters);
	$opt = array();

	foreach ($arr AS $key => $val)
	{
		$opt[] = array('value' => $val['goods_id'],
		'text' => $val['goods_name'],
		'data' => $val['shop_price']);
	}

	make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 把商品加入关联
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'add_link_goods')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	check_authz_json('edit_goods');

	$linked_array   = $json->decode($_GET['add_ids']);
	$linked_goods   = $json->decode($_GET['JSON']);
	$goods_id       = $linked_goods[0];
	$is_double      = $linked_goods[1] == true ? 0 : 1;

	foreach ($linked_array AS $val)
	{
		if ($is_double)
		{
			/* 双向关联 */
			$sql = "INSERT INTO " . $os->table('link_goods') . " (goods_id, link_goods_id, is_double, admin_id) " .
			"VALUES ('$val', '$goods_id', '$is_double', '$_SESSION[admin_id]')";
			$db->query($sql, 'SILENT');
		}

		$sql = "INSERT INTO " . $os->table('link_goods') . " (goods_id, link_goods_id, is_double, admin_id) " .
		"VALUES ('$goods_id', '$val', '$is_double', '$_SESSION[admin_id]')";
		$db->query($sql, 'SILENT');
	}

	$linked_goods   = get_linked_goods($goods_id);
	$options        = array();

	foreach ($linked_goods AS $val)
	{
		$options[] = array('value'  => $val['goods_id'],
		'text'      => $val['goods_name'],
		'data'      => '');
	}

	clear_cache_files();
	make_json_result($options);
}

/*------------------------------------------------------ */
//-- 删除关联商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_link_goods')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	check_authz_json('edit_goods');

	$drop_goods     = $json->decode($_GET['drop_ids']);
	$drop_goods_ids = db_create_in($drop_goods);
	$linked_goods   = $json->decode($_GET['JSON']);
	$goods_id       = $linked_goods[0];
	$is_signle      = $linked_goods[1];

	if (!$is_signle)
	{
		$sql = "DELETE FROM " .$os->table('link_goods') .
		" WHERE link_goods_id = '$goods_id' AND goods_id " . $drop_goods_ids;
	}
	else
	{
		$sql = "UPDATE " .$os->table('link_goods') . " SET is_double = 0 ".
		" WHERE link_goods_id = '$goods_id' AND goods_id " . $drop_goods_ids;
	}
	if ($goods_id == 0)
	{
		$sql .= " AND admin_id = '$_SESSION[admin_id]'";
	}
	$db->query($sql);

	$sql = "DELETE FROM " .$os->table('link_goods') .
	" WHERE goods_id = '$goods_id' AND link_goods_id " . $drop_goods_ids;
	if ($goods_id == 0)
	{
		$sql .= " AND admin_id = '$_SESSION[admin_id]'";
	}
	$db->query($sql);

	$linked_goods = get_linked_goods($goods_id);
	$options      = array();

	foreach ($linked_goods AS $val)
	{
		$options[] = array(
		'value' => $val['goods_id'],
		'text'  => $val['goods_name'],
		'data'  => '');
	}

	clear_cache_files();
	make_json_result($options);
}

/*------------------------------------------------------ */
//-- 增加一个配件
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_group_goods')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	check_authz_json('edit_goods');

	$fittings   = $json->decode($_GET['add_ids']);
	$arguments  = $json->decode($_GET['JSON']);
	$goods_id   = $arguments[0];
	$price      = $arguments[1];

	foreach ($fittings AS $val)
	{
		$sql = "INSERT INTO " . $os->table('group_goods') . " (parent_id, goods_id, goods_price, admin_id) " .
		"VALUES ('$goods_id', '$val', '$price', '$_SESSION[admin_id]')";
		$db->query($sql, 'SILENT');
	}

	$arr = get_group_goods($goods_id);
	$opt = array();

	foreach ($arr AS $val)
	{
		$opt[] = array('value'      => $val['goods_id'],
		'text'      => $val['goods_name'],
		'data'      => '');
	}

	clear_cache_files();
	make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 删除一个配件
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'drop_group_goods')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	check_authz_json('edit_goods');

	$fittings   = $json->decode($_GET['drop_ids']);
	$arguments  = $json->decode($_GET['JSON']);
	$goods_id   = $arguments[0];
	$price      = $arguments[1];

	$sql = "DELETE FROM " .$os->table('group_goods') .
	" WHERE parent_id='$goods_id' AND " .db_create_in($fittings, 'goods_id');
	if ($goods_id == 0)
	{
		$sql .= " AND admin_id = '$_SESSION[admin_id]'";
	}
	$db->query($sql);

	$arr = get_group_goods($goods_id);
	$opt = array();

	foreach ($arr AS $val)
	{
		$opt[] = array('value'      => $val['goods_id'],
		'text'      => $val['goods_name'],
		'data'      => '');
	}

	clear_cache_files();
	make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 搜索文章
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'get_article_list')
{
	check_authz_json('edit_goods');
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$filters =(array) $json->decode($_GET['JSON']);

	$where = " WHERE cat_id > 0 ";
	if (!empty($filters['title']))
	{
		$keyword  = trim($filters['title']);
		$where   .=  " AND title LIKE '%" . mysql_like_quote($keyword) . "%' ";
	}

	$sql        = 'SELECT article_id, title FROM ' .$os->table('article'). $where.
	'ORDER BY article_id DESC LIMIT 50';
	$res        = $db->query($sql);
	$arr        = array();

	while ($row = $db->fetchRow($res))
	{
		$arr[]  = array('value' => $row['article_id'], 'text' => $row['title'], 'data'=>'');
	}

	make_json_result($arr);
}

/*------------------------------------------------------ */
//-- 添加关联文章
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add_goods_article')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	check_authz_json('edit_goods');

	$articles   = $json->decode($_GET['add_ids']);
	$arguments  = $json->decode($_GET['JSON']);
	$goods_id   = $arguments[0];

	foreach ($articles AS $val)
	{
		$sql = "INSERT INTO " . $os->table('goods_article') . " (goods_id, article_id, admin_id) " .
		"VALUES ('$goods_id', '$val', '$_SESSION[admin_id]')";
		$db->query($sql);
	}

	$arr = get_goods_articles($goods_id);
	$opt = array();

	foreach ($arr AS $val)
	{
		$opt[] = array('value'      => $val['article_id'],
		'text'      => $val['title'],
		'data'      => '');
	}

	clear_cache_files();
	make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 删除关联文章
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drop_goods_article')
{
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	check_authz_json('edit_goods');

	$articles   = $json->decode($_GET['drop_ids']);
	$arguments  = $json->decode($_GET['JSON']);
	$goods_id   = $arguments[0];

	$sql = "DELETE FROM " .$os->table('goods_article') . " WHERE " . db_create_in($articles, "article_id");
	$db->query($sql);

	$arr = get_goods_articles($goods_id);
	$opt = array();

	foreach ($arr AS $val)
	{
		$opt[] = array('value'      => $val['article_id'],
		'text'      => $val['title'],
		'data'      => '');
	}

	clear_cache_files();
	make_json_result($opt);
}
elseif ($_REQUEST['act'] == 'get_color_list'){
	check_authz_json('edit_goods');
	//modified 2009-03-24  fillbag
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$filters = $json->decode($_GET['JSON']);
	$arr = search_color_spec_list($filters);

	$opt = array();

	foreach ($arr AS $key => $val){
		$opt[] = array_merge(array('value' => $val['color_id'],'text'  => $val['color_name']),array_slice($val, 1));
	}
	make_json_result($opt);
}elseif ($_REQUEST['act'] == 'get_size_list'){
	check_authz_json('edit_goods');
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$filters = $json->decode($_GET['JSON']);

	$arr = get_size_list($filters);
	$opt = array();

	foreach ($arr AS $key => $val)
	{
		$opt[] = array('value' => $val['size_id'],
		'text'  => $val['size_name'],
		'data'  => '');
	}

	make_json_result($opt);
}elseif($_REQUEST['act'] == 'add_color_list'){
	check_authz_json('edit_goods');
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$color_ids   = $json->decode($_GET['add_ids']);
	$arguments  = $json->decode($_GET['JSON']);
	$goods_id = $arguments[0];

	$sql = "SELECT * FROM ".$os->table('color')." c LEFT JOIN ".$os->table('color_lib')." cl ON c.img_id=cl.img_id WHERE ".db_create_in($color_ids,'color_id');
	//$sql = "SELECT * FROM ".$os->table('color')." WHERE ".db_create_in($color_ids,'color_id');
	$res = $db->query($sql);
	while ($row = $db->fetchRow($res)) {
		$db->query("INSERT INTO " . $os->table('goods_color') . "(goods_id,color_id,color_name,img_id) VALUES('$goods_id','$row[color_id]','$row[color_name]','$row[img_id]')");
	}
	$g_c_list = $db->getAll("SELECT gc.color_id,gc.color_name,gc.goods_color_id,cl.img_id,cl.img_name,cl.img_code,cl.img_file FROM " .
	$os->table('goods_color') . " gc LEFT JOIN " . $os->table('color_lib') .
	" cl ON gc.img_id=cl.img_id WHERE gc.goods_id='$goods_id' ORDER BY gc.goods_color_id ASC");
	//    $g_c_list = $db->getAll("SELECT gc.color_id,gc.color_name,gc.goods_color_id,c.* FROM " .
	//                            $os->table('goods_color') . " gc LEFT JOIN " . $os->table('color') .
	//                            " c ON gc.color_id=c.color_id WHERE gc.goods_id='$goods_id' ORDER BY gc.goods_color_id ASC");

	foreach ($g_c_list as $val){
		$img_item = '';
		if(!empty($val['img_file']))
		$img_item = '<img src="'.$_CFG['pre_fetch_img'].$val['img_file'].'?16,16" width="16" height="16" border="0" alt="'.$val['img_name'].'"/>';
		$val['img_item'] = $img_item;
		$opt[] = array_merge(array('value' => $val['color_id'], 'text'  => $val['color_name']), array_slice($val, 1));
	}

	make_json_result($opt);
}elseif($_REQUEST['act']=='drop_color_list'){
	check_authz_json('edit_goods');
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$color_ids   = $json->decode($_GET['drop_ids']);
	$arguments  = $json->decode($_GET['JSON']);
	$goods_id = $arguments[0];
	$db->query("DELETE FROM ".$os->table('goods_color')." WHERE goods_id='$goods_id' AND ".db_create_in($color_ids, "color_id"));

	make_json_result('successful');
}elseif($_REQUEST['act']=='drop_color'){
	check_authz_json('edit_goods');
	$g_c_id =intval($_GET['del_id']);
	$db->query("DELETE FROM ".$os->table('goods_color')." WHERE goods_color_id='$g_c_id'");

	make_json_result('successful');
}elseif($_REQUEST['act']=='set_color_ext'){
	check_authz_json('edit_goods');
	$color_id =intval($_GET['color_id']);
	$goods_id =intval($_GET['goods_id']);
	$g_c_row = $db->getRow("SELECT img_name,img_code,img_file FROM ".$os->table('goods_color')." WHERE goods_id='$goods_id' AND color_id='$color_id'");
	$img_item = '<img src="'.$_CFG['pre_fetch_img'].$g_c_row['img_file'].'?16,16" width="16" height="16" border="0" alt='.$g_c_row['img_name'].' />';
	$g_c_row['img_item'] = $img_item;
	$g_c_row['row_indexid'] = intval($_GET['row_indexid']);
	make_json_result($g_c_row);
}elseif($_REQUEST['act'] == 'add_size_list'){
	check_authz_json('edit_goods');
	include_once(ROOT_PATH . 'includes/cls_json.php');
	$json = new JSON;

	$size_ids   = $json->decode($_GET['add_ids']);
	$arguments  = $json->decode($_GET['JSON']);

	$sql = "SELECT size_id,size_name FROM " . $os->table('size') . " WHERE " . db_create_in($size_ids, "size_id");
	$arr = $db->getAll($sql);

	$opt = array();

	foreach ($arr AS $key => $val)
	{
		$opt[] = array('value' => $val['size_id'],
		'text'  => $val['size_name'],
		'data'  => '');
	}

	make_json_result($opt);
}
/**
 * 列表链接
 * @param   bool    $is_add         是否添加（插入）
 * @param   string  $extension_code 虚拟商品扩展代码，实体商品为空
 * @return  array('href' => $href, 'text' => $text)
 */
function list_link($is_add = true, $extension_code = '')
{
	$href = 'goods.php?act=list';
	if (!empty($extension_code))
	{
		$href .= '&extension_code=' . $extension_code;
	}
	if (!$is_add)
	{
		$href .= '&' . list_link_postfix();
	}
	if ($extension_code == 'virtual_card')
	{
		$text = '虚拟卡列表';
	}
	else
	{
		$text = '商品列表';
	}
	return array('href' => $href, 'text' => $text);
}

/**
 * 添加链接
 * @param   string  $extension_code 虚拟商品扩展代码，实体商品为空
 * @return  array('href' => $href, 'text' => $text)
 */
function add_link($extension_code = '')
{
	$href = 'goods.php?act=add';
	if (!empty($extension_code))
	{
		$href .= '&extension_code=' . $extension_code;
	}

	if ($extension_code == 'virtual_card')
	{
		$text = '添加新虚拟卡';
	}
	else
	{
		$text = '添加新商品';
	}

	return array('href' => $href, 'text' => $text);
}

/**
 * 检查图片网址是否合法
 *
 * @param string $url 网址
 *
 * @return boolean
 */
function goods_parse_url($url)
{
	$parse_url = @parse_url($url);
	return (!empty($parse_url['scheme']) && !empty($parse_url['host']));
}

/**
 * 保存某商品的优惠价格
 * @param   int     $goods_id    商品编号
 * @param   array   $number_list 优惠数量列表
 * @param   array   $price_list  价格列表
 * @return  void
 */
function handle_volume_price($goods_id, $number_list, $price_list)
{
	$sql = "DELETE FROM " . $GLOBALS['os']->table('volume_price') .
	" WHERE price_type = '1' AND goods_id = '$goods_id'";
	$GLOBALS['db']->query($sql);


	/* 循环处理每个优惠价格 */
	foreach ($price_list AS $key => $price)
	{
		/* 价格对应的数量上下限 */
		$volume_number = $number_list[$key];

		if (!empty($price))
		{
			$sql = "INSERT INTO " . $GLOBALS['os']->table('volume_price') .
			" (price_type, goods_id, volume_number, volume_price) " .
			"VALUES ('1', '$goods_id', '$volume_number', '$price')";
			$GLOBALS['db']->query($sql);
		}
	}
}

?>